#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include "StdUdp.h"


StdUdpServer::StdUdpServer(const char *ip, unsigned short port)
{
    m_sock = socket(AF_INET,SOCK_DGRAM,0);
    if(m_sock < 0)
    {
        perror("socket");
        close(m_sock);
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;//IPV4协议族
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip);
    if(bind(m_sock,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("bind");
        close(m_sock);
    }
}

StdUdpServer::~StdUdpServer()
{
    close(m_sock);
}

bool StdUdpServer::UdpSRecv(void *ptr, size_t size)
{
    struct sockaddr_in clientAddr;
    socklen_t len = sizeof(clientAddr);

    if(recvfrom(m_sock,ptr,size,0,(struct sockaddr*)&clientAddr,&len) < 0)
    {
        perror("recvfrom");
        return false;
    }
    printf("客户端IP:%s 端口:%d\n",inet_ntoa(clientAddr.sin_addr),ntohs(clientAddr.sin_port));
    return true;
}

bool StdUdpServer::UdpSSend(const char *ip, unsigned short port, void *ptr, size_t size)
{
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;//IPV4协议族
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip);

    if(sendto(m_sock,ptr,size,0,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("sendto");
        return false;
    }
    return true;
}

StdUdpClient::StdUdpClient(const char *ip, unsigned short port)
{
    m_sock = socket(AF_INET,SOCK_DGRAM,0);
    if(m_sock < 0)
    {
        perror("socket");
        close(m_sock);
    }

    strcpy(m_ServerIP,ip);
    m_Port = port;
}

StdUdpClient::~StdUdpClient()
{
    close(m_sock);
}

bool StdUdpClient::UdpCRecv(void *ptr, size_t size)
{
    struct sockaddr_in clientAddr;
    socklen_t len = sizeof(clientAddr);

    if(recvfrom(m_sock,ptr,size,0,(struct sockaddr*)&clientAddr,&len) < 0)
    {
        perror("recvfrom");
        return false;
    }
    
    return true;
}

bool StdUdpClient::UdpCSend(void *ptr, size_t size)
{
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;//IPV4协议族
    addr.sin_port = htons(m_Port);
    addr.sin_addr.s_addr = inet_addr(m_ServerIP);

    if(sendto(m_sock,ptr,size,0,(struct sockaddr*)&addr,sizeof(addr)) < 0)
    {
        perror("sendto");
        return false;
    }
    return true;
}
